import { useDispatch, useSelector } from 'react-redux'
import { checkAllTodo } from '../../store/actions/todo'
import TodoItem from '../TodoItem'
export default function TodoMain() {
  const dispatch = useDispatch()
  const list = useSelector((state) => {
    if (state.filter.active === 'completed') {
      // 保留已完成的
      return state.todo.filter((item) => item.done)
    } else if (state.filter.active === 'active') {
      // 保留未完成的
      return state.todo.filter((item) => !item.done)
    }
    return state.todo
  })
  const allList = useSelector((state) => state.todo)
  // !先确定全选的状态，根据所有的单选状态来判断
  const isChecked = allList.every((item) => item.done)
  const handleChangeAll = () => dispatch(checkAllTodo(!isChecked))
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isChecked}
        onChange={handleChangeAll}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <TodoItem key={item.id} item={item} />
        ))}
      </ul>
    </section>
  )
}
